from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.utils import timezone
from datetime import date
from django.db import models

from .models import KnowledgeNode, LearningPath, PathNode, StudyRecord, ReviewTask
from .serializers import (
    KnowledgeNodeSerializer,
    LearningPathSerializer,
    LearningPathDetailSerializer,
    PathNodeSerializer,
    StudyRecordSerializer,
    ReviewTaskSerializer
)
from .services import LearningProgressService, ReviewScheduler


class KnowledgeNodeViewSet(viewsets.ModelViewSet):
    """知识节点视图集"""
    serializer_class = KnowledgeNodeSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return KnowledgeNode.objects.filter(user=self.request.user)

    @action(detail=True, methods=['get'])
    def graph(self, request, pk=None):
        """获取知识节点的图结构"""
        node = self.get_object()

        def build_node_data(n, visited=None):
            if visited is None:
                visited = set()
            if n.id in visited:
                return None
            visited.add(n.id)

            return {
                'id': n.id,
                'name': n.name,
                'type': n.node_type,
                'mastery_level': n.mastery_level,
                'prerequisites': [
                    build_node_data(pre, visited)
                    for pre in n.prerequisites.all()
                    if pre.id not in visited
                ]
            }

        graph_data = build_node_data(node)
        return Response(graph_data)

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取学习统计"""
        queryset = self.get_queryset()
        return Response({
            'total_nodes': queryset.count(),
            'mastered_nodes': queryset.filter(mastery_level__gte=80).count(),
            'learning_nodes': queryset.filter(mastery_level__gt=0, mastery_level__lt=80).count(),
            'not_started_nodes': queryset.filter(mastery_level=0).count(),
            'average_mastery': queryset.aggregate(models.Avg('mastery_level'))['mastery_level__avg'] or 0,
        })


class LearningPathViewSet(viewsets.ModelViewSet):
    """学习路径视图集"""
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return LearningPath.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return LearningPathDetailSerializer
        return LearningPathSerializer

    @action(detail=True, methods=['post'])
    def start(self, request, pk=None):
        """开始学习路径"""
        path = self.get_object()
        if path.status == 'not_started':
            path.status = 'in_progress'
            path.started_at = timezone.now()
            path.save()

            # 解锁第一个节点
            first_node = path.pathnode_set.order_by('order').first()
            if first_node:
                first_node.status = 'available'
                first_node.save()

        return Response({
            'message': '学习路径已开始',
            'path': LearningPathSerializer(path).data
        })

    @action(detail=True, methods=['post'])
    def complete(self, request, pk=None):
        """完成学习路径"""
        path = self.get_object()
        path.status = 'completed'
        path.progress = 100
        path.completed_at = timezone.now()
        path.save()
        return Response({'message': '学习路径已完成'})

    @action(detail=True, methods=['post'])
    def pause(self, request, pk=None):
        """暂停学习路径"""
        path = self.get_object()
        path.status = 'paused'
        path.save()
        return Response({'message': '学习路径已暂停'})

    @action(detail=True, methods=['post'])
    def resume(self, request, pk=None):
        """恢复学习路径"""
        path = self.get_object()
        path.status = 'in_progress'
        path.save()
        return Response({'message': '学习路径已恢复'})


class StudyRecordViewSet(viewsets.ModelViewSet):
    """学习记录视图集"""
    serializer_class = StudyRecordSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return StudyRecord.objects.filter(user=self.request.user)

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取学习统计"""
        from django.db.models import Sum
        from datetime import timedelta

        queryset = self.get_queryset()
        today = date.today()

        return Response({
            'total_minutes': queryset.aggregate(Sum('duration_minutes'))['duration_minutes__sum'] or 0,
            'today_minutes': queryset.filter(created_at__date=today).aggregate(Sum('duration_minutes'))['duration_minutes__sum'] or 0,
            'this_week_minutes': queryset.filter(created_at__date__gte=today - timedelta(days=today.weekday())).aggregate(Sum('duration_minutes'))['duration_minutes__sum'] or 0,
            'total_records': queryset.count(),
        })

    def perform_create(self, serializer):
        record = serializer.save(user=self.request.user)
        service = LearningProgressService(self.request.user)
        service.handle_study_record(record)


class ReviewTaskViewSet(viewsets.ModelViewSet):
    """复习任务视图集"""
    serializer_class = ReviewTaskSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = ReviewTask.objects.filter(user=self.request.user)

        # 按状态筛选
        status_filter = self.request.query_params.get('status')
        if status_filter:
            queryset = queryset.filter(status=status_filter)

        return queryset

    @action(detail=False, methods=['get'])
    def today(self, request):
        """获取今日复习任务"""
        today = date.today()
        tasks = self.get_queryset().filter(scheduled_date=today, status='pending')
        serializer = self.get_serializer(tasks, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def complete_task(self, request, pk=None):
        """完成复习任务"""
        task = self.get_object()
        task.status = 'completed'
        task.completed_at = timezone.now()
        task.save()
        scheduler = ReviewScheduler(request.user)
        scheduler.schedule_for_node(task.node, reference_date=task.scheduled_date)
        return Response({'message': '复习任务已完成'})

    @action(detail=True, methods=['post'])
    def skip(self, request, pk=None):
        """跳过复习任务"""
        task = self.get_object()
        task.status = 'skipped'
        task.save()
        return Response({'message': '已跳过该复习任务'})
